package niuke;

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */
//在二叉树中找到两个节点的最近公共祖先
public class Solution12 {
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
        // write code here
        TreeNode ret = dfs(root, o1, o2);
        return ret.val;
        
    }

    public TreeNode dfs( TreeNode root, int o1, int o2){
        //递归终止条件
        if(root == null || root.val == o1 || root.val == o2) return root;
        TreeNode left = dfs(root.left, o1, o2);
        TreeNode right = dfs(root.right, o1,o2);
        //如果left 为空, 说明两个值都在右子树上
        if( left == null) return right;
        //在左子树上
        if( right == null) return left;
        //都不为空, 说明在根节点
        return root;
    }
}